package com.mz361.modules.system.service.impl;

import com.mz361.common.data.PageSort;
import com.mz361.common.enums.StatusEnum;
import com.mz361.modules.system.domain.Company;
import com.mz361.modules.system.repository.CompanyRepository;
import com.mz361.modules.system.service.CompanyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.persistence.EntityManager;
import javax.persistence.TypedQuery;
import javax.persistence.criteria.CriteriaBuilder;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @author liaomch
 * @date 2024/05/07
 */
@Service
public class CompanyServiceImpl implements CompanyService {

    @Autowired
    private CompanyRepository companyRepository;

    @Autowired
    EntityManager entityManager;

    /**
     * 根据ID查询数据
     *
     * @param id 主键ID
     */
    @Override
    public Company getById(Long id) {
        return companyRepository.findById(id).orElse(null);
    }

    @Override
    public Long countBySourceKey(String sourceKey) {
        return companyRepository.countBySourceKey(sourceKey);
    }

    @Override
    public Long countByInviteCode(String inviteCode) {
        return companyRepository.countByInviteCode(inviteCode);
    }

    @Override
    public Company getByCompanyNum(String companyNum) {
        return companyRepository.findByCompanyNum(companyNum);
    }

    /**
     * 获取分页列表数据
     *
     * @param example 查询实例
     * @return 返回分页数据
     */
    @Override
    public Page<Company> getPageList(Example<Company> example) {
        // 创建分页对象
        PageRequest page = PageSort.pageRequest();
        return companyRepository.findAll(example, page);
    }

    /**
     * 保存数据
     *
     * @param company 实体对象
     */
    @Override
    public Company save(Company company) {
        return companyRepository.save(company);
    }

    /**
     * 状态(启用，冻结，删除)/批量状态处理
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Boolean updateStatus(StatusEnum statusEnum, List<Long> idList) {
        return companyRepository.updateStatus(statusEnum.getCode(), idList) > 0;
    }

    @Override
    public Long countAll() {
        return companyRepository.countAll();
    }

    @Override
    public Map<String, Long> countCompanyGroupByAreaCode() {
        CriteriaBuilder cb = entityManager.getCriteriaBuilder();
        CriteriaQuery<Object[]> cq = cb.createQuery(Object[].class);
        Root<Company> root = cq.from(Company.class);

        // 选择userType和计数
        cq.multiselect(
                root.get("areaCode"),
                cb.count(root)
        );

        // 分组
        cq.groupBy(root.get("areaCode"));

        TypedQuery<Object[]> query = entityManager.createQuery(cq);
        List<Object[]> results = query.getResultList();

        // 将查询结果转换为Map
        Map<String, Long> groupByMap = results.stream()
                .collect(Collectors.toMap(
                        row -> (String) row[0], // 用户类型作为key
                        row -> (Long) row[1]  // 计数作为value
                ));

        return groupByMap;
    }

    @Override
    public List<Company> getCompanyList() {
        return companyRepository.findAll();
    }

}